﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;

namespace Alfa.Common.ValidationRules {
	public class PeselValidationRule : ValidationRuleBase {
		readonly int[] PeselWeights;

		public PeselValidationRule( ) {
			PeselWeights = new int[] { 1, 3, 7, 9, 1, 3, 7, 9, 1, 3 };
		}

		public bool Nullable { get; set; }

		public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo) {
			if (value != null && value is string && (string)value != "") {
				var textValue = (string)value;

				List<int> numbers = new List<int>( );

				foreach (var character in textValue.ToArray( )) {
					int number;
					if (int.TryParse(character.ToString( ), out number))
						numbers.Add(number);
					else
						return this.ParseError(false, Messages.NotANumber + ".");
				}

				if (numbers.Count < 11)
					return this.ParseError(false, Messages.PeselNumberTooShort + ".");
				if (numbers.Count > 11)
					return this.ParseError(false, Messages.PeselNumberTooLong + ".");

				int hash = 0;
				for (int i = 0; i < numbers.Count - 1; i++) {
					hash += (numbers[i] * PeselWeights[i]) % 10;
				}

				hash %= 10;
				hash = 10 - hash;

				if (numbers[10] == hash)
					return this.ParseError(true, null);
				else
					return this.ParseError(false, Messages.InvalidPeselNumber + ".");
			} else
				return this.ParseError(true, null);
		}
	}
}
